/**

 * @Description Ext.translate for ExtJS 2.x and 3.x; Auto translation with Google Translation API (java/php server side)
 * @author  Tomislav Milkovic
 * @license LGPLv3 http://www.opensource.org/licenses/lgpl-3.0.html
 * @version 1.6, 20.09.2009.
 */

/**
 * @updated 11.07.2009 completely rewritten code 
 * @description Internal logic is rewritten to optimize for faster execution.
 * 				For all translation, Ext.translate.Cache is responsible.
 * 
 * @updated 16.08.2009 Translate ColumnModel 
 * @description Translation for Grid ColumnModel added
 *
 * @updated 24.08.2009 Ext.QuickTips. 
 * @description Translation for Ext.QuickTips is added
 *
 * @updated 24.08.2009 Ext.QuickTips. 
 * @description Translation for Ext.QuickTips is added
 */

 /** 
  * Global functions for all Components.
  * Here is implemented all Ext.Component text field updating functions.
  * Name of the function must have the same name as field/property to be translated.
  * 
  *  This is valid for custom and standard fields/properties.
  */
Ext.translate.globalFn = {

	fieldLabel : function(text) {
		if (this.rendered) {
			var dom = this.el.up('.x-form-item', 10, true);
			if (defined( dom ))
				dom.child('.x-form-item-label').update(text);

		} else {
			this.fieldLabel = text;
		} 
	},
	
	boxLabel : function(boxLabel) {
	
		if (this.rendered) {
			var dom = this.wrap.child('.x-form-cb-label');
			if (defined(dom ))
				dom.update(boxLabel);
		} else {
			this.boxLabel = boxLabel;
		}
	},
	
	title : function(title) {
		if (Ext.isFunction(this['setTitle']))
		this.setTitle(title);
		if (Ext.isObject(this.tabEl)){
			//@todo updatetebbet items
			//this.tabEl.
		}
	},
	
	text : function(text) {
		if (Ext.isFunction(this['setText']))
		this.setText(text);
	},
	
	tooltip : function(text){
		if (Ext.isFunction(this['setTooltip']))
		this.setTooltip(text);
	},
	
	html : function(text){
		if (Ext.isDefined(this.body))
			this.body.update( Ext.DomHelper.markup(text) );
	}
};


/**
 * Override for all GUI components adding to them auto translation support.
 * When component is created, all registered fields will and it's values will be saved in 
 * cache Ext.translate.Cache for later translation. 
 * After cached data is translated, this.translate() function can be called to 
 * retrieve and update translated texts to the component
 */
/**
 * @events beforestoretocache    - before field value is saved to cache; 
 * 				@return boolean - if false continues to another field
 * 				@params this - caller of event
 * 						object - contains field and field value { 'value' : value, 'field' : field}
 * 
 *         beforeupdatetranslate - before translation is set to the field
 *         		return : boolean - if false continues to another field
 *         		@params this 	 - caller of event
 *         				cacheobj - object from cache containing tranlsation pairs 
 *         				field	 - component field which receives translation
 *         				isCustom - is custom field translation 
 */				
Ext.override(Ext.Component, {

	/**
	 * Every object can have additional nonstandard fields to be translated 
	 * */
	translateItems : null,

	/**
	 *  original texts will be saved here prior translations
	 * */
	translateStore : null,
	
	/**
	 * callback function to be called when translation of nonstandard fields
	 * */
	translateCallbackFn : null,

	/**
	 * Is translation for this object enabled 
	 * */
	isTranslate : true,	
	
    initComponent : function(){	

	    this.translateStore = {};
	    this.translateItems = [];
	    
	    if (!this.isTranslate) return ;
	    
	    if (!Ext.translate.isInitialized()) return;
	    
	    this.addEvents('beforestoretocache', 'beforeupdatetranslate');
	    	    		
	    this.prepareTranslate();
		
	},

	prepareTranslate : function(){
		
		this.translateStore = {};
	    this.translateItems = [];
	    
	    if(!this.isTranslate) return;
		var result = false;
		var options2 = { 'propArray': this.translateItems,'isCustom': true };		
		result = this.cacheFields(options2);		
		
		var options = { 'propArray': Ext.translate.map_gui,'isCustom': false };
		result = result || this.cacheFields(options);	
		
		//if column model exists, translate
		//this.cacheCM(options);

		if (result){				
			this.translate();	
		};
	},
	

	/**
	 * Main method for component translation
	 * */
	translate : function(childs) {

			if (!this.isTranslate) return ;
		
			var options2 = { 'propArray': this.translateItems, 'isCustom': true };		
			this.translateFields(options2);		
			
			var options = { 'propArray': Ext.translate.map_gui, 'isCustom' : false};
			this.translateFields(options);
			
			if (childs===true) {
				if ( !((Ext.isObject(this.items)) && (Ext.isArray(this.items.items))) ) return;
				var fn = function(item,index,allItems){
					if(!Ext.translate.translating){return false;};
					if (Ext.isFunction(item.translate)){
						item.translate(childs);
					};					
				};
				Ext.each( this.items.items ,fn,this);

			};
	},
	
	/**
	 * search in cache for every translated field and update component
	 * @private 
	 * */
	translateFields : function(options) {	
		if(!this.isTranslate) return;
        var cacheobj;
        for (var field in this.translateStore){
        		if(!Ext.translate.translating){break;};
                var id = this.translateStore[field];
                if (typeof id == 'number') {
                        cacheobj = Ext.translate.Cache.getTranslationByID(id);
                        if (Ext.type(cacheobj) == 'object')     {
                                if (Ext.type(cacheobj[Ext.translate.currentLanguage])=='string') {
                                                this.fireEvent('beforeupdatetranslate', this,cacheobj,field,options.isCustom);
                                                this.translateLocalData(cacheobj,field,options);
                                }
                        }
                } 
        }				
	},	
	
	
	/**
	 * Each text field will be saved to cache.
	 * @private 
	 * */
	cacheFields : function(options) {
			if(!this.isTranslate) return;
			var result = false;	

		   //translate next field; if not exists then exit
			var field ;
			var value ;
			var len = options.propArray.length;
			var cnt = 0;
			
			while (true){
				field = options.propArray[cnt];
				if (cnt == len) {
					return result;
				}
							
				value = this[field];			
				cnt = cnt + 1;
				
				//if empty, go to next field
				if (!Ext.isString(value)) continue;
				if (value.trim().length==0) continue;
				result = true;				
				var obj = { 'value' : value, 'field' : field};
				if (!this.fireEvent('beforestoretocache', this,obj)) continue;
				var callback = undefined;
				if (Ext.translate.clientonly===true){
					callback = {callback : this.translateLocalData,
								scope : this,
								params : [field,options]};
				};
				
				 this.translateStore[field] = Ext.translate.Cache.setTranslation(obj,callback);						
			};
			
	},
		
	/** 
	 * Update component property and DOM element to new text value.
	 * Field name is used as a mapping to function name in Ext.translate.globalFn.
	 * If field is called 'fieldLabel' function Ext.translate.globalFn.fieldLabel(data)
	 * will be 0128called to update current component.
	 * */
	translateLocalData : function(cacheobj, field,options) {
		 this[field] = cacheobj[Ext.translate.currentLanguage];
		 
		if (options.isCustom == true) {
			if (Ext.isFunction(this.translateCallbackFn))
				this.translateCallbackFn(null, true, { 	'responseText' : this[field]}, field);
			return;
		}
		
		if(!this.rendered) return;
		
		if (Ext.isFunction(Ext.translate.globalFn[field])) {
			Ext.translate.globalFn[field].call(this,this[field]);
		}
	}
	
});



Ext.grid.ColumnModel = Ext.interceptConstructor(Ext.grid.ColumnModel, function(config) {
    var o = {fields : ['header','tooltip'], replace : false};
    Ext.translate.Cache.setTranslationCustom(config,o);
});

Ext.grid.ColumnModel.prototype.getColumnHeaderOrig = Ext.grid.ColumnModel.prototype.getColumnHeader;
Ext.grid.ColumnModel.prototype.getColumnTooltipOrig = Ext.grid.ColumnModel.prototype.getColumnTooltip;

Ext.override(Ext.grid.ColumnModel,{

	getTranslated : function(col,fld){
		
		if(Ext.isArray(this.config[col].translateStore)){
			var idx = this.config[col].translateStore[fld];
			if (!defined(idx)) return undefined;
			var obj = Ext.translate.Cache.getTranslationByID(idx);
			return obj[Ext.translate.currentLanguage];
		};
		
		var oval = this[arguments.caller+'Orig'](col);
		var cfg = {language : Ext.translate.currentLanguage, value : oval};
		var tran =  Ext.translate.Cache.getTranslation(cfg);
		return tran;
	},
		
	getColumnHeader : function(col){		
		return this.getTranslated(col,'header');
	},
	
	getColumnTooltip : function(col){
		return this.getTranslated(col,'tooltip');
	}
	
});


Ext.QuickTips.register = Ext.QuickTips.register.createInterceptor(function() {
	var obj = arguments[0];
	obj.cache = Ext.translate.Cache.setTranslation({value : obj.text, language : Ext.translate.defaultLanguage });
	return true;
	});

Ext.QuickTip.prototype.onTargetOver = Ext.QuickTip.prototype.onTargetOver.createInterceptor(function() {
	if (this.activeTarget) {
		var obj = Ext.translate.Cache.getTranslationByID(this.activeTarget.cache);
		if (obj) this.activeTarget.text = obj[Ext.translate.currentLanguage];
	}
	return true;
}); 
